<!-- 层级资源浏览器组件 - 信号级→功能级数据树 -->
<template>
  <div class="hierarchy-browser">
    <div class="browser-header">
      <div class="header-title">
        <el-icon><FolderOpened /></el-icon>
        <span>数据层级</span>
      </div>
      <div class="header-actions">
        <el-button size="small" text @click="expandAll">
          <el-icon><Plus /></el-icon>
        </el-button>
        <el-button size="small" text @click="collapseAll">
          <el-icon><Minus /></el-icon>
        </el-button>
      </div>
    </div>

    <div class="tree-container">
      <el-tree
        ref="treeRef"
        :data="treeData"
        :props="treeProps"
        :expand-on-click-node="false"
        :default-expanded-keys="defaultExpandedKeys"
        node-key="id"
        class="data-tree"
        @node-click="handleNodeClick"
        @node-expand="handleNodeExpand"
        @node-collapse="handleNodeCollapse"
      >
        <template #default="{ node, data }">
          <div class="tree-node">
            <div class="node-icon">
              <el-icon v-if="data.type === 'folder'"><Folder /></el-icon>
              <el-icon v-else-if="data.type === 'signal'" class="signal-icon"><Cpu /></el-icon>
              <el-icon v-else-if="data.type === 'function'" class="function-icon"><Operation /></el-icon>
              <el-icon v-else-if="data.type === 'device'" class="device-icon"><Monitor /></el-icon>
              <el-icon v-else-if="data.type === 'analysis'" class="analysis-icon"><TrendCharts /></el-icon>
              <el-icon v-else-if="data.type === 'processed'" class="processed-icon"><Setting /></el-icon>
              <el-icon v-else><Document /></el-icon>
            </div>
            <div class="node-content">
              <span class="node-name">{{ data.name }}</span>
              <div class="node-meta">
                <el-tag 
                  v-if="data.count" 
                  size="small" 
                  type="info"
                  class="count-tag"
                >{{ data.count }}</el-tag>
                <el-tag 
                  v-if="data.size" 
                  size="small" 
                  type="success"
                  class="size-tag"
                >{{ data.size }}</el-tag>
                <span 
                  v-if="data.location" 
                  class="location-info"
                >
                  <el-icon><Location /></el-icon>{{ data.location }}
                </span>
              </div>
            </div>
            <div class="node-actions" v-if="!node.isLeaf">
              <el-button 
                size="small" 
                text 
                @click.stop="toggleExpand(node)"
                class="expand-btn"
              >
                <el-icon v-if="node.expanded"><ArrowDown /></el-icon>
                <el-icon v-else><ArrowRight /></el-icon>
              </el-button>
            </div>
          </div>
        </template>
      </el-tree>
    </div>

    <!-- 数据统计卡片 -->
    <div class="stats-section">
      <div class="stats-title">数据统计</div>
      <div class="stats-grid">
        <div class="stat-card signal-stat">
          <div class="stat-icon">
            <el-icon><Cpu /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ signalCount }}</div>
            <div class="stat-label">信号级</div>
          </div>
        </div>
        <div class="stat-card function-stat">
          <div class="stat-icon">
            <el-icon><Operation /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ functionCount }}</div>
            <div class="stat-label">功能级</div>
          </div>
        </div>
        <div class="stat-card device-stat">
          <div class="stat-icon">
            <el-icon><Monitor /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ deviceCount }}</div>
            <div class="stat-label">设备</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 过滤器 -->
    <div class="filter-section">
      <div class="filter-title">快速过滤</div>
      <div class="filter-options">
        <el-checkbox-group v-model="activeFilters" @change="handleFilterChange">
          <el-checkbox label="signals">信号级</el-checkbox>
          <el-checkbox label="functions">功能级</el-checkbox>
          <el-checkbox label="devices">设备</el-checkbox>
          <el-checkbox label="analysis">分析结果</el-checkbox>
        </el-checkbox-group>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import {
  FolderOpened,
  Plus,
  Minus,
  Folder,
  Cpu,
  Operation,
  Monitor,
  TrendCharts,
  Setting,
  Document,
  Location,
  ArrowDown,
  ArrowRight
} from '@element-plus/icons-vue'

// Props
const props = defineProps({
  treeData: {
    type: Array,
    default: () => []
  }
})

// Emits
const emit = defineEmits(['nodeSelect', 'nodeExpand'])

// 组件引用
const treeRef = ref(null)

// 数据状态
const defaultExpandedKeys = ref(['signals', 'functions'])
const activeFilters = ref(['signals', 'functions'])
const filteredTreeData = ref([])

// 树形组件配置
const treeProps = {
  children: 'children',
  label: 'name'
}

// 计算统计数据
const signalCount = computed(() => {
  return countNodesByType(props.treeData, 'signal')
})

const functionCount = computed(() => {
  return countNodesByType(props.treeData, 'function')
})

const deviceCount = computed(() => {
  return countNodesByType(props.treeData, 'device')
})

// 统计节点数量
function countNodesByType(nodes, type) {
  let count = 0
  
  function traverse(nodeList) {
    nodeList.forEach(node => {
      if (node.type === type) {
        count++
      }
      if (node.children) {
        traverse(node.children)
      }
    })
  }
  
  traverse(nodes)
  return count
}

// 过滤树形数据
function filterTreeData(data, filters) {
  if (filters.length === 0) return data
  
  function filterNodes(nodes) {
    return nodes.filter(node => {
      // 如果是根节点，保留
      if (node.type === 'folder') {
        const filteredChildren = node.children ? filterNodes(node.children) : []
        return filteredChildren.length > 0 ? { ...node, children: filteredChildren } : null
      }
      
      // 根据过滤条件判断
      const shouldShow = filters.some(filter => {
        switch (filter) {
          case 'signals':
            return node.type === 'signal' || (node.children && node.children.some(child => child.type === 'signal'))
          case 'functions':
            return node.type === 'function' || (node.children && node.children.some(child => child.type === 'function'))
          case 'devices':
            return node.type === 'device'
          case 'analysis':
            return node.type === 'analysis'
          default:
            return true
        }
      })
      
      if (shouldShow) {
        const filteredChildren = node.children ? filterNodes(node.children) : []
        return { ...node, children: filteredChildren }
      }
      
      return null
    }).filter(Boolean)
  }
  
  return filterNodes(data)
}

// 节点点击处理
const handleNodeClick = (data, node) => {
  emit('nodeSelect', data)
  ElMessage.success(`选中节点: ${data.name}`)
}

// 节点展开处理
const handleNodeExpand = (data, node) => {
  emit('nodeExpand', data)
}

// 节点收起处理
const handleNodeCollapse = (data, node) => {
  console.log('节点收起:', data.name)
}

// 切换展开状态
const toggleExpand = (node) => {
  if (node.expanded) {
    treeRef.value.store.nodesMap[node.key].collapse()
  } else {
    treeRef.value.store.nodesMap[node.key].expand()
  }
}

// 全部展开
const expandAll = () => {
  const getAllKeys = (data) => {
    let keys = []
    data.forEach(item => {
      keys.push(item.id)
      if (item.children) {
        keys = keys.concat(getAllKeys(item.children))
      }
    })
    return keys
  }
  
  const allKeys = getAllKeys(props.treeData)
  allKeys.forEach(key => {
    const node = treeRef.value.store.nodesMap[key]
    if (node && !node.isLeaf) {
      node.expand()
    }
  })
  ElMessage.success('已展开所有节点')
}

// 全部收起
const collapseAll = () => {
  const getAllKeys = (data) => {
    let keys = []
    data.forEach(item => {
      keys.push(item.id)
      if (item.children) {
        keys = keys.concat(getAllKeys(item.children))
      }
    })
    return keys
  }
  
  const allKeys = getAllKeys(props.treeData)
  allKeys.forEach(key => {
    const node = treeRef.value.store.nodesMap[key]
    if (node && !node.isLeaf) {
      node.collapse()
    }
  })
  ElMessage.success('已收起所有节点')
}

// 过滤器变化处理
const handleFilterChange = (value) => {
  console.log('过滤器变化:', value)
  nextTick(() => {
    // 更新树形数据显示
    filteredTreeData.value = filterTreeData(props.treeData, value)
  })
}

// 监听数据变化
watch(() => props.treeData, (newData) => {
  filteredTreeData.value = filterTreeData(newData, activeFilters.value)
}, { immediate: true, deep: true })
</script>

<style scoped>
.hierarchy-browser {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #263445;
  padding: 1vh 1vw;
}

/* 浏览器头部 */
.browser-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 1vh 0;
  border-bottom: 1px solid #2d3a4b;
  margin-bottom: 1vh;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 0.5vw;
  color: #bfcbd9;
  font-weight: 600;
  font-size: 1rem;
}

.header-actions {
  display: flex;
  gap: 0.5vw;
}

/* 树形容器 */
.tree-container {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  margin-bottom: 2vh;
}

/* 树形组件样式 */
.data-tree {
  background: transparent;
}

.data-tree :deep(.el-tree-node__content) {
  background: transparent;
  border-radius: 0.5vh;
  margin: 0.2vh 0;
  padding: 0.8vh;
  transition: all 0.2s ease;
}

.data-tree :deep(.el-tree-node__content:hover) {
  background: #2d3a4b;
}

.data-tree :deep(.el-tree-node.is-current > .el-tree-node__content) {
  background: rgba(64, 158, 255, 0.2);
  border-left: 0.3vw solid #409EFF;
}

.data-tree :deep(.el-tree-node__expand-icon) {
  color: #8591a3;
}

.data-tree :deep(.el-tree-node__expand-icon.is-leaf) {
  display: none;
}

/* 树节点样式 */
.tree-node {
  display: flex;
  align-items: center;
  width: 100%;
  gap: 0.8vw;
}

.node-icon {
  display: flex;
  align-items: center;
  font-size: 1.2rem;
  width: 2vw;
  justify-content: center;
}

.signal-icon {
  color: #67C23A;
}

.function-icon {
  color: #409EFF;
}

.device-icon {
  color: #E6A23C;
}

.analysis-icon {
  color: #F56C6C;
}

.processed-icon {
  color: #909399;
}

.node-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 0.3vh;
}

.node-name {
  color: #bfcbd9;
  font-size: 0.9rem;
  font-weight: 500;
}

.node-meta {
  display: flex;
  align-items: center;
  gap: 0.5vw;
  flex-wrap: wrap;
}

.count-tag, .size-tag {
  font-size: 0.7rem;
  height: 1.8vh;
  line-height: 1.8vh;
}

.location-info {
  display: flex;
  align-items: center;
  gap: 0.2vw;
  color: #8591a3;
  font-size: 0.7rem;
}

.node-actions {
  display: flex;
  align-items: center;
}

.expand-btn {
  color: #8591a3;
  font-size: 0.8rem;
  padding: 0.3vh;
  min-height: auto;
}

/* 统计卡片 */
.stats-section {
  margin-bottom: 2vh;
}

.stats-title {
  color: #bfcbd9;
  font-size: 0.9rem;
  font-weight: 600;
  margin-bottom: 1vh;
  padding: 0.5vh 0;
  border-bottom: 1px solid #2d3a4b;
}

.stats-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 1vh;
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 1vw;
  padding: 1vh;
  background: #1f2d3d;
  border-radius: 0.5vh;
  border-left: 0.3vw solid;
  transition: all 0.2s ease;
}

.stat-card:hover {
  background: #2d3a4b;
  transform: translateX(0.2vw);
}

.signal-stat {
  border-left-color: #67C23A;
}

.function-stat {
  border-left-color: #409EFF;
}

.device-stat {
  border-left-color: #E6A23C;
}

.stat-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.2rem;
  color: #bfcbd9;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 1.1rem;
  font-weight: 600;
  color: #bfcbd9;
  line-height: 1.2;
}

.stat-label {
  font-size: 0.7rem;
  color: #8591a3;
  line-height: 1.2;
}

/* 过滤器部分 */
.filter-section {
  border-top: 1px solid #2d3a4b;
  padding-top: 1vh;
}

.filter-title {
  color: #bfcbd9;
  font-size: 0.9rem;
  font-weight: 600;
  margin-bottom: 1vh;
}

.filter-options {
  display: flex;
  flex-direction: column;
  gap: 0.5vh;
}

/* 滚动条样式 */
.tree-container::-webkit-scrollbar {
  width: 0.6vw;
}

.tree-container::-webkit-scrollbar-track {
  background: #1f2d3d;
  border-radius: 0.3vw;
}

.tree-container::-webkit-scrollbar-thumb {
  background: #2d3a4b;
  border-radius: 0.3vw;
  transition: background 0.3s ease;
}

.tree-container::-webkit-scrollbar-thumb:hover {
  background: #409EFF;
}

/* Element Plus 组件深色主题覆盖 */
.hierarchy-browser :deep(.el-checkbox) {
  color: #bfcbd9 !important;
}

.hierarchy-browser :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #409EFF !important;
  border-color: #409EFF !important;
}

.hierarchy-browser :deep(.el-checkbox__inner) {
  background-color: #263445 !important;
  border-color: #2d3a4b !important;
}

.hierarchy-browser :deep(.el-checkbox__inner:hover) {
  border-color: #409EFF !important;
}

.hierarchy-browser :deep(.el-button) {
  background: transparent !important;
  border: none !important;
  color: #8591a3 !important;
  padding: 0.5vh !important;
}

.hierarchy-browser :deep(.el-button:hover) {
  color: #409EFF !important;
}

.hierarchy-browser :deep(.el-tag) {
  background: #1f2d3d !important;
  border-color: #2d3a4b !important;
  color: #8591a3 !important;
}

.hierarchy-browser :deep(.el-tag--info) {
  background: #1f2d3d !important;
  border-color: #2d3a4b !important;
  color: #909399 !important;
}

.hierarchy-browser :deep(.el-tag--success) {
  background: #1f4838 !important;
  border-color: #2d5a41 !important;
  color: #67C23A !important;
}
</style>